package com.cqan.lang;

/**
 * 
 * byte相关操作工具方法
 * 
 * 2013上午10:24:17 Created by @author slaton
 * 
 * @since 1.0
 * 
 */
public class ByteUtils {

	/**
	 * 取byte[]start至start+len位转换成int值返回
	 * 
	 * @param b
	 * @param start
	 *            起始位
	 * @param len
	 *            截取长度
	 * @return 返回转换成的int值
	 */
	public static int bytes2Int(byte[] b, int start, int len) {
		int sum = 0;
		int end = start + len;
		for (int i = start; i < end; i++) {
			int n = ((int) b[i]) & 0xff;
			n <<= (--len) * 8;
			sum = n + sum;
		}
		return sum;
	}

	/**
	 * 把int值转成长度为len的byte数组
	 * 
	 * @param value
	 * @param len
	 * @return
	 */
	public static byte[] int2Bytes(int value, int len) {

		byte[] b = new byte[len];
		for (int i = 0; i < len; i++) {
			b[len - i - 1] = (byte) ((value >> 8 * i) & 0xff);
		}
		return b;
	}

	/**
	 * byte数组转成字符串
	 * 
	 * @param b
	 * @param start
	 * @param len
	 * @return
	 */
	public static String bytes2String(byte[] b, int start, int len) {
		return new String(b, start, len);
	}

	/**
	 * 二进制数组转成16进制字符串
	 * @param b
	 * @return
	 */
	public static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs.append(0).append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString().toUpperCase();
	}

}
